<?php
/**
 * Copyright Morph 2008
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @filesource
 * @category    Tool
 * @package     Morph
 * @link        http://www.mor.ph
 * @since       v 0.0.1
 */

class MorphIni
{
    /**
     * Parsed INI container
     * @var private
     */
    private    $__ini = array();

    /**
     * Container for Morph's default DB information.
     * @var private
     */
    private    $__db_section = 'database';

    /**
     * Default configuration name
     *
     * NOTE: You can test this library locally before deploying to Morph AppSpace.
     * 		 Create a local file e.g. morph.ini and dump the following contents
     * 		 in INI format @see php.ini.
     *
     * 		 Filename : morph.ini
     * 		 Contents :
     * 					[database]
     * 					db_hostname = "your_db_host"     # localhost or IP Address
     * 					db_port = 3306                   # e.g. for MySQL or 5432 for PostgreSQL
     * 					db_type = "mysql"                # mysql or pgsql
     * 					db_username = "<yourdbusername>"
     * 					db_password = "<yourdbpassword>"
     *
     * 		 And do the following when you create an instance of this class.
     * 		 e.g.
     * 			$Morph = new MorphIni('/path/to/morph.ini');
     *
     * @private
     */
    private    $__default_config = 'morph.ini';

    /**
     * class constructor for Morph INI parser.
     *
     * NOTE: If you're deploying your PHP application into the Morph AppSpace
     * 		 do not supply a value in the constructor parameter.
     *
     * @param 	string  $config should be in fullpath if not using the default Morph config
     * @return	object
     */
    function __construct($config = '')
    {
        if (empty($config)) {
        	  $sapi_type = php_sapi_name(); 
        	  if (substr($sapi_type, 0, 3) == 'cli') {
        	  	$app_path = explode("releases",dirname(__FILE__));
        	  	$config = $app_path[0] . "shared/bin/{$this->__default_config}";
        	  } else {
	            $paths = ini_get('open_basedir');
	            $app_path = explode(":", $paths);
	            $config = $app_path[0]."/shared/bin/{$this->__default_config}";
        	  }
        }

        if ($this->isOk($config)) {
            $ini = parse_ini_file($config, true); # parse INI file with section
            $ini_obj = parse_ini_file($config); # parse INI file without section
            if ($ini != false && $ini_obj != false) {
                $this->__ini = $ini;
                $this->iniToObj($ini_obj);
            } else {
                die("ERROR: Invalid configuration file : " . __FILE__ . " on line : " . __LINE__);
            }
        } else {
            die("ERROR: Loading INI configuration file : " . __FILE__ . " on line : " . __LINE__);
        }
    }

    /**
     * Returns a value of a particular key in a sector of the INI file
     *
     * @param  string  $section of the INI
     * @param  string  $key of the section
     * @return mixed   $value of the key  otherise false
     */
    public function get($section, $key)
    {
        if (!empty($section) && !empty($key)) {
            if (array_key_exists($key, $this->__ini[$section]))
                return $this->__ini[$section][$key];
            echo "ERROR: $key on $section does not exist!";
        } else {
            echo "ERROR: INI section and key is required : " . __FILE__ . " on line : " . __LINE__;
        }
        return false;
    }

    /**
     * Returns a key value specifically from the "database" section of the INI file
     *
     * @example INI contents
     *
     * <code>
     *     [database]
     *     db_hostname = "localhost"
     *     db_port = 3306
     *     db_name = "dbname"
     *     db_type = "mysql"
     *     db_username = "dbusername"
     *     db_password = "dbpassword"
     * </code>
     *
     * @param  string  key of the "db_section"
     * @return mixed   key value otherwise false
     */
    public function getDb($key)
    {
        if (array_key_exists($key, $this->__ini[$this->__db_section])) {
            return $this->__ini[$this->__db_section][$key];
        }
        return false;
    }

    /**
     * Basic validation
     *
     * @param  string  the INI configuration $file
     * @return boolean true/false
     */
    private function isOk($file)
    {
        if (!file_exists($file) && !is_readable($file)) {
            return false;
        }
        return true;
    }

    /**
     * Attaches the INI key and value as class members
     */
    private function iniToObj($ini)
    {
        foreach($ini as $k => $v) {
            $this->$k = $v;
        }
    }
}
?>